package com.uniview.util;

import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.uniview.enums.EUploadFileType;

/**
 * 文件上传工具类
 * 
 */
public class UploadFileUtils {

	private static Logger log = Logger.getLogger(UploadFileUtils.class);

	/**
	 * 文件上传
	 * 
	 * @param file
	 * @param request
	 * @return
	 */
	public static List<String> uploadFile(CommonsMultipartFile file, HttpServletRequest request, EUploadFileType ufType)
			throws Exception {
		// 定义解析器去解析request
		CommonsMultipartResolver mutilpartResolver = new CommonsMultipartResolver(
				request.getSession().getServletContext());
		// request如果是Multipart类型
		if (mutilpartResolver != null && mutilpartResolver.isMultipart(request)) {
			// 强转成 MultipartHttpServletRequest
			MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
			String seqId = request.getParameter("userId");
			if (StringUtils.isBlank(seqId)) { // 若用户ID为空，则生成UUID
				seqId = UUID.randomUUID().toString().replaceAll("-", "");
			}
			// 获取文件名
			Iterator<String> it = multiRequest.getFileNames();
			List<String> fNames = new ArrayList<String>();
			while (it.hasNext()) {
				// 获取MultipartFile类型文件
				MultipartFile fileDetail = multiRequest.getFile(it.next());
				if (fileDetail != null && StringUtils.isNotBlank(fileDetail.getOriginalFilename())) {
					String uPath = "";
					if (ufType != null) {
						uPath += ufType.toString() + "/";
					}
					uPath += seqId + "/";
					String fName = fileDetail.getOriginalFilename();
					String gPath = request.getServletContext().getRealPath("/") + "upload" + "/" + uPath;
					log.debug("path:" + gPath + "/" + fName);
					if (new File(gPath + fName).exists())
						new File(gPath + fName).delete();

					// 判断文件夹是否存在
					File _file = new File(gPath);
					if (!_file.exists())
						_file.mkdirs();
					File upFile = new File(gPath + fName);
					// 将上传文件写入到指定文件中
					fileDetail.transferTo(upFile);

					if (EUploadFileType.ATT == ufType && (fName.toLowerCase().endsWith(".zip")
							|| fName.toLowerCase().endsWith(".rar") || fName.toLowerCase().endsWith(".tar"))) {
						// 解附件中的压缩包文件
						ZipRarUtil.unAll(gPath + fName, gPath, true);
					}
					// 记录附件存储的相对路径
					fNames.add(uPath + fName);
				}
			}
			return fNames;
		}
		return null;
	}

}
